package com.easy.work.fragment;

import android.annotation.SuppressLint;
import android.content.DialogInterface;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.SparseArray;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.base.syslib.Logs;
import com.base.syslib.impl.OnSelectCityImpl;
import com.base.syslib.impl.OnSelectProCityImpl;
import com.base.syslib.pulltorefresh.PullToRefreshBase;
import com.base.syslib.pulltorefresh.PullToRefreshListView;
import com.base.syslib.util.MessageTools;
import com.base.syslib.view.viewpager.CarouseFigureBean;
import com.base.syslib.view.viewpager.CycleViewPager;
import com.easy.work.MainActivity;
import com.easy.work.R;
import com.easy.work.app.AppSession;
import com.easy.work.app.BaseFragment;
import com.easy.work.app.CommonValue;
import com.easy.work.app.MyApplication;
import com.easy.work.bean.WorkBaseInfo;
import com.easy.work.function.JobFilterListAct;
import com.easy.work.function.WebViewAct;
import com.easy.work.function.city.ProvinceAct;
import com.easy.work.function.main.JobSearchActivity;
import com.easy.work.function.main.WorkBaseDetailAct;
import com.easy.work.function.main.adapter.MainListAdapter;
import com.easy.work.function.mall.activity.JobFilterActivity;
import com.easy.work.function.mall.bean.ExchangeEvent;
import com.easy.work.function.mall.bean.JobCommonBean;
import com.easy.work.http.BaseResponse;
import com.easy.work.http.HttpClient;
import com.easy.work.http.request.CarouseFigureRequest;
import com.easy.work.http.request.JobFilterRequest;
import com.easy.work.http.request.WorkBaseListInfoRequest;
import com.easy.work.http.response.CarouseFigureList;
import com.easy.work.http.response.ResumeInfoResponse;
import com.easy.work.http.response.WorkBaseListInfoList;
import com.easy.work.utils.ViewFactory;
import com.easy.work.view.dialog.CityDialog;
import com.easy.work.view.dialog.ProCityDialog;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;

/**
 * Created by Admin on 2017/12/6.
 */
public class MainFragment extends BaseFragment implements PullToRefreshBase.OnRefreshListener<ListView> {
    @BindView(R.id.listView)
    PullToRefreshListView refreshListView;
    @BindView(R.id.left_back)
    LinearLayout leftBack;
    @BindView(R.id.i_serch)
    LinearLayout iSerch;
    @BindView(R.id.titlebar)
    LinearLayout titlebar;
    @BindView(R.id.tv_city)
    TextView tvCity;
    @BindView(R.id.rl_to_top)
    RelativeLayout rlToTop;
    Unbinder unbinder;

    /**
     * 招聘列表
     */
    List<WorkBaseInfo> workBaseInfoList = new ArrayList<>();
    MainListAdapter adapter;
    ListView listView;

    //listview的顶部head
    View headerView;
    /**
     * 广告页面数据
     */
    public List<CarouseFigureBean> ADInfoList = new ArrayList<>();

    @Override
    public int getFragmentLayout() {
        return R.layout.main_refresh_view;
    }

    private CycleViewPager cycleViewPager;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        // TODO: inflate a fragment view
        View rootView = super.onCreateView(inflater, container, savedInstanceState);
        unbinder = ButterKnife.bind(this, rootView);
        initView(rootView);

        refreshListView.doPullRefreshing(true, 0);
        return rootView;
    }

    void initView(View view) {
        adapter = new MainListAdapter(getContext(), workBaseInfoList);
        refreshListView.setPullLoadEnabled(true);
        refreshListView.setPullRefreshEnabled(true);
        refreshListView.setOnRefreshListener(this);


        listView = refreshListView.getRefreshableView();
        listView.setHeaderDividersEnabled(false);
        listView.setDividerHeight(0);

        listView.setOnScrollListener(new AbsListView.OnScrollListener() {

            private SparseArray recordSp = new SparseArray(0);

            private int mCurrentfirstVisibleItem = 0;

            @Override
            public void onScrollStateChanged(AbsListView view, int scrollState) {
            }


            @Override
            public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
                mCurrentfirstVisibleItem = firstVisibleItem;
                View firstView = view.getChildAt(0);

                if (null != firstView) {
                    ItemRecod itemRecord = (ItemRecod) recordSp.get(firstVisibleItem);
                    if (null == itemRecord) {
                        itemRecord = new ItemRecod();
                    }

                    itemRecord.height = firstView.getHeight();
                    itemRecord.top = firstView.getTop();
                    recordSp.append(firstVisibleItem, itemRecord);
                }
                int scroolY = getScrollY();

                int toolbarHeight = titlebar.getBottom();

                //当滑动的距离 <= toolbar高度的时候，改变Toolbar背景色的透明度，达到渐变的效果
                if (scroolY <= toolbarHeight) {
                    float scale = (float) scroolY / toolbarHeight;
                    float alpha = scale * 255;
                    titlebar.setBackgroundColor(Color.argb((int) alpha, 255, 144, 00));
//                    iSerch.setBackgroundColor(Color.argb((int) alpha, 255, 255, 255));
                } else {
                    //上述虽然判断了滑动距离与toolbar高度相等的情况，但是实际测试时发现，标题栏的背景色
                    //很少能达到完全不透明的情况，所以这里又判断了滑动距离大于toolbar高度的情况，
                    //将标题栏的颜色设置为完全不透明状态
                    titlebar.setBackgroundColor(Color.argb(255, 255, 144, 00));
//                    iSerch.setBackgroundColor(0xffffff);
                }

            }


            private int getScrollY() {
                int height = 0;
                for (int i = 0; i < mCurrentfirstVisibleItem; i++) {
                    ItemRecod itemRecod = (ItemRecod) recordSp.get(i);
                    if (itemRecod != null) {
                        height += itemRecod.height;
                    }


                }
                ItemRecod itemRecod = (ItemRecod) recordSp.get(mCurrentfirstVisibleItem);
                if (null == itemRecod) {
                    itemRecod = new ItemRecod();
                }
                return height - itemRecod.top;
            }


            class ItemRecod {
                int height = 0;
                int top = 0;
            }
        });
        headerView = View.inflate(getActivity(), R.layout.frag_main, null);
        cycleViewPager = (CycleViewPager) getActivity().getFragmentManager()
                .findFragmentById(R.id.main_viewPager);
        findHeadView(headerView);

        listView.addHeaderView(headerView);

        listView.setAdapter(adapter);

        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                WorkBaseInfo baseInfo = (WorkBaseInfo) parent.getAdapter().getItem(position);
                WorkBaseDetailAct.start(getContext(), baseInfo.workId);
            }
        });

        AppSession.setPullFormartRefreshTime(refreshListView);
        refreshListView.doPullRefreshing(true, 0);

        rlToTop.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                listView.smoothScrollToPosition(0);
            }
        });

        proCityDialog = new ProCityDialog(getContext()).builder().setPositiveButton("确定", new OnSelectProCityImpl() {

            @Override
            public void selectCity(String cityName, String cityCode) {
                tvCity.setText(cityName);
                AppSession.getInstance().setCityName(cityName);
                AppSession.getInstance().setCityCode(cityCode);
                ((MyApplication) getActivity().getApplication()).locationService.stop();
                refreshListView.doPullRefreshing(true, 0);

            }
        }).setNegativeButton("取消");
    }


    /**
     * 头部布局初始化
     *
     * @param view
     */
    private void findHeadView(View view) {
        LinearLayout rl_fujinzhiwei = (LinearLayout) view.findViewById(R.id.rl_fujinzhiwei);
        LinearLayout rl_rementuijian = (LinearLayout) view.findViewById(R.id.rl_rementuijian);
        LinearLayout rl_zuixinfabu = (LinearLayout) view.findViewById(R.id.rl_zuixinfabu);
        LinearLayout rl_zhiweishaixuan = (LinearLayout) view.findViewById(R.id.rl_zhiweishaixuan);

        rl_fujinzhiwei.setOnClickListener(iconListener);
        rl_rementuijian.setOnClickListener(iconListener);
        rl_zuixinfabu.setOnClickListener(iconListener);
        rl_zhiweishaixuan.setOnClickListener(iconListener);

    }

    private View.OnClickListener iconListener = new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            JobFilterRequest request = new JobFilterRequest();
            switch (view.getId()) {
                case R.id.rl_fujinzhiwei:
                    request.searchType = "2";

                    getSearchList(request, "附近职位");
//                    JobFilterActivity.start(getActivity());
                    break;
                case R.id.rl_rementuijian:
                    request.searchType = "3";
                    getSearchList(request, "热门推荐");
//                    JobFilterActivity.start(getActivity());
                    break;
                case R.id.rl_zuixinfabu:
                    request.searchType = "1";
                    getSearchList(request, "最新发布");
                    break;
                case R.id.rl_zhiweishaixuan:
                    JobFilterActivity.start(getActivity());
                    break;
            }
        }
    };

    private void getSearchList(final JobFilterRequest request, String title) {
//        request.city = AppSession.getInstance().getCityCode();
//        request.latitude = AppSession.getInstance().getLatitude();
//        request.longitude = AppSession.getInstance().getLontitude();
        JobFilterListAct.start(getContext(), title, request);
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        unbinder.unbind();
    }

    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {

                case 1:
                    leftBack.setClickable(true);
                    break;
            }
        }
    };

    private ProCityDialog proCityDialog;

    @OnClick({R.id.left_back, R.id.i_serch})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.left_back:
//                ProvinceAct.start(getContext());
                leftBack.setClickable(false);
                mHandler.sendEmptyMessageDelayed(1, 3 * 1000);
                proCityDialog.show();

                break;
            case R.id.i_serch:
                JobSearchActivity.start(getActivity());
                break;
        }
    }

    /**
     * 加载位置坐标
     */
    private int currentPage = 0;

    /**
     * 获取招聘信息列表
     */
    private void getRecommendSubject() {
//        final WorkBaseListInfoRequest request = new WorkBaseListInfoRequest();
        final JobFilterRequest request = new JobFilterRequest();
        request.start = adapter.getCount();
        request.limit = 8;
        request.city = AppSession.getInstance().getCityCode();
        request.latitude = AppSession.getInstance().getLatitude();
        request.longitude = AppSession.getInstance().getLontitude();
//        request.searchType = "0";
        request.searchType = "2";
        HttpClient.post(request, new HttpClient.onSuccessListener() {
            @Override
            public void onSuccess(BaseResponse response) {

                Logs.e("mainfragment", "response");
                WorkBaseListInfoList recommendList = (WorkBaseListInfoList) response;
                if (recommendList != null && recommendList.list != null && recommendList.list.size() > 0) {

                    List<WorkBaseInfo> addList = recommendList.list;
                    workBaseInfoList.addAll(addList);
                }
                adapter.notifyDataSetChanged();
                refreshListView.onPullUpRefreshComplete();
                refreshListView.onPullDownRefreshComplete();

            }
        }, new HttpClient.onFailListener() {
            @Override
            public void onFail(int code, String msg) {
                Logs.d("MainFragment", "WorkBaseListInfoRequest    code" + code + "      msg=" + msg);
            }
        });

    }

    /**
     * 获取轮播广告业信息
     */
    private void getAD() {
        final CarouseFigureRequest request = new CarouseFigureRequest();
        request.type = "1";
        HttpClient.post(request, new HttpClient.onSuccessListener() {
            @Override
            public void onSuccess(BaseResponse response) {
                Logs.e("mainfragment", response.toString());
                CarouseFigureList carouseFigureList = (CarouseFigureList) response;
                ADInfoList = carouseFigureList.list;
//                    ADInfoList = carouseFigureEntity.body;
                initialize(ADInfoList);
                refreshListView.onPullUpRefreshComplete();
                refreshListView.onPullDownRefreshComplete();
            }
        }, new HttpClient.onFailListener() {
            @Override
            public void onFail(int code, String msg) {
            }
        });

    }

    /**
     * 加载轮播图
     *
     * @param infos
     */
    @SuppressLint("NewApi")
    private void initialize(List<CarouseFigureBean> infos) {
        if (infos == null || infos.size() < 1) {
            return;
        }

        List<ImageView> views = new ArrayList<ImageView>();
        // 将最后一个ImageView添加进来
        views.add(ViewFactory.getImageView(getContext(), infos.get(infos.size() - 1).imgAddress));
        for (int i = 0; i < infos.size(); i++) {
            views.add(ViewFactory.getImageView(getContext(), infos.get(i).imgAddress));
        }
        // 将第一个ImageView添加进来
        views.add(ViewFactory.getImageView(getContext(), infos.get(0).imgAddress));

        // 设置循环，在调用setData方法前调用
        cycleViewPager.setCycle(true);

        // 在加载数据前设置是否循环
        cycleViewPager.setData(views, infos, mAdCycleViewListener);
        //设置轮播
        cycleViewPager.setWheel(true);

        // 设置轮播时间，默认5000ms
        cycleViewPager.setTime(2000);
        //设置圆点指示图标组居中显示，默认靠右
        cycleViewPager.setIndicatorCenter();
    }

    private CycleViewPager.ImageCycleViewListener mAdCycleViewListener = new CycleViewPager.ImageCycleViewListener() {

        @Override
        public void onImageClick(CarouseFigureBean info, int position, View imageView) {
            if (cycleViewPager.isCycle()) {
                position = position - 1;
//                WebViewAct.start(getContext(), ADInfoList.get(position).eventUrl);
                CarouseFigureBean bean = ADInfoList.get(position);
                WebViewAct.start(getContext(), bean.eventUrl, "易上班");
            }
        }

    };

    @Override
    public void onPullDownToRefresh(PullToRefreshBase<ListView> refreshView) {
        currentPage = 0;
        workBaseInfoList.clear();
        getAD();
        getRecommendSubject();
    }

    @Override
    public void onPullUpToRefresh(PullToRefreshBase<ListView> refreshView) {
        currentPage++;
        getRecommendSubject();
    }

    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);
        if (hidden) {
            //隐藏时所作的事情
            EventBus.getDefault().unregister(this);


        } else {
            //显示时所作的事情
            EventBus.getDefault().register(this);
            String cityName = AppSession.getInstance().getCityName();
            tvCity.setText(cityName);
        }
    }


    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onExchangeEvent(JobCommonBean.ItemsEntity cityEntity) {
        tvCity.setText(cityEntity.text);
    }


}
